package com.dymall.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dymall.common.api.CartClient;
import com.dymall.common.api.ProductClient;
import com.dymall.common.api.UserClient;
import com.dymall.common.domain.dto.AddressDTO;
import com.dymall.common.domain.dto.ItemDTO;
import com.dymall.common.domain.dto.OrderDetailDTO;
import com.dymall.common.exception.BadRequestException;
import com.dymall.common.exception.BizIllegalException;
import com.dymall.common.util.UserContext;
import com.dymall.order.domain.dto.OrderFormDTO;
import com.dymall.order.domain.po.Order;
import com.dymall.order.domain.po.OrderDetail;
import com.dymall.order.domain.po.OrderLogistics;
import com.dymall.order.mapper.OrderMapper;
import com.dymall.order.service.IOrderDetailService;
import com.dymall.order.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: chakgai
 * @Description: TODO
 * @DateTime: 2025/2/13 22:48
 **/
@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    private final ProductClient productClient;
    private final IOrderDetailService detailService;
    private final CartClient cartClient;
    private final UserClient userClient;

    private final OrderLogisticsServiceImpl orderLogisticsService;

    @Override
    @Transactional
    public Long createOrder(OrderFormDTO orderFormDTO) {
        // 1. 初始化订单数据
        Order order = new Order();

        // 1.1. 获取订单商品详情
        List<OrderDetailDTO> detailDTOS = orderFormDTO.getDetails();

        // 1.2. 提取商品ID及对应数量的映射关系
        Map<Long, Integer> itemNumMap = detailDTOS.stream()
                .collect(Collectors.toMap(OrderDetailDTO::getItemId, OrderDetailDTO::getNum));
        Set<Long> itemIds = itemNumMap.keySet();

        // 1.3. 查询对应商品信息
        List<ItemDTO> items = productClient.queryItemByIds(itemIds);
        if (items == null || items.size() < itemIds.size()) {
            throw new BadRequestException("部分商品不存在");
        }

        // 1.4. 计算商品总价
        int total = items.stream()
                .mapToInt(item -> item.getPrice() * itemNumMap.get(item.getId()))
                .sum();
        order.setTotalFee(total);

        // 1.5. 设置订单其他基本属性
        order.setPaymentType(orderFormDTO.getPaymentType());
        order.setUserId(UserContext.getUser());
        order.setStatus(1);

        // 1.6. 将订单保存至数据库
        save(order);

        // 2. 保存订单商品详情
        List<OrderDetail> details = new ArrayList<>(items.size());
        for (ItemDTO item : items) {
            OrderDetail detail = new OrderDetail();
            detail.setName(item.getName());
            detail.setPrice(item.getPrice());
            detail.setNum(itemNumMap.get(item.getId()));
            detail.setItemId(item.getId());
            detail.setOrderId(order.getId());
            details.add(detail);
        }
        detailService.saveBatch(details);

        // 3. 清理购物车中的商品
        cartClient.deleteCartItemByIds(itemIds);

        // 4. 扣减库存
        try {
            productClient.deductStock(detailDTOS);
        } catch (Exception e) {
            throw new BizIllegalException("库存不足，无法完成订单！");
        }

        // 5. 远程调用用户服务获取地址信息
        AddressDTO selectedAddress = userClient.findAddressById(orderFormDTO.getAddressId());
        if (selectedAddress == null) {
            throw new BadRequestException("地址信息不存在");
        }

        // 6. 存储物流信息到物流表
        OrderLogistics logistics = new OrderLogistics();
        logistics.setOrderId(order.getId());
        logistics.setContact(selectedAddress.getContact());
        logistics.setMobile(selectedAddress.getMobile());
        logistics.setProvince(selectedAddress.getProvince());
        logistics.setCity(selectedAddress.getCity());
        logistics.setTown(selectedAddress.getTown());
        logistics.setStreet(selectedAddress.getStreet());

        // 保存物流信息到物流表
        orderLogisticsService.save(logistics);


        // 返回订单ID
        return order.getId();
    }


    /**
     *     标记订单为已支付
      */
    @Override
    @Transactional
    public boolean markOrderPaid(Long orderId) {
        Order order = getById(orderId);
        if (order == null) {
            throw new BadRequestException("订单不存在");
        }
        // 更新订单状态为已支付
        order.setStatus(2);
        // 生成随机交易号
        String transactionId = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        order.setTransactionId(transactionId);  // 设置交易号
        return updateById(order);
    }
}
